﻿<div id="app" class="container">
    <!-- 加载提示 -->
    <el-loading v-if="loading" fullscreen text="提交中..."></el-loading>

    <!-- 表单区域 -->
    <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px" style="margin-top: 20px;">
        <!-- 基础信息 -->
        <el-divider content-position="left">基础信息</el-divider>
        <el-row>
            <el-col :span="12">
                <el-form-item label="盘点单号" prop="inventory_order_no">
                    <el-input v-model="formData.inventory_order_no" readonly placeholder="自动生成"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="盘点类型" prop="inventory_types">
                    <el-select v-model="formData.inventory_types" placeholder="请选择">
                        <el-option label="存货盘点" value="存货盘点"></el-option>
                        <el-option label="定期盘点" value="定期盘点"></el-option>
                        <el-option label="临时盘点" value="临时盘点"></el-option>
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="12">
                <el-form-item label="开始时间" prop="inventory_start_time">
                    <el-date-picker v-model="formData.inventory_start_time"
                                    type="date"
                                    placeholder="选择日期"
                                    value-format="yyyy-MM-dd">
                    </el-date-picker>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="结束时间" prop="stkt_end_time">
                    <el-date-picker v-model="formData.stkt_end_time"
                                    type="date"
                                    placeholder="选择日期"
                                    value-format="yyyy-MM-dd">
                    </el-date-picker>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="12">
                <el-form-item label="仓库名称" prop="warehouse_name">
                    <el-select v-model="formData.warehouse_name"
                               placeholder="请选择仓库"
                               v-on:change="checkWarehouseLock"
                               filterable
                               clearable>
                        <el-option v-for="warehouse in warehouseList"
                                   :key="warehouse.warehouse_id"
                                   :label="warehouse.warehouse_name"
                                   :value="warehouse.warehouse_name">
                            <span>{{ warehouse.warehouse_name }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">
                                {{ warehouse.warehouse_status === '1' ? '正常' : '锁定' }}
                            </span>
                        </el-option>
                    </el-select>
                    <div v-if="formData.warehouse_name" style="margin-top: 5px;">
                        <el-tag v-if="warehouseLocked" type="warning" size="small">仓库已锁定</el-tag>
                        <el-tag v-else type="info" size="small">仓库未锁定</el-tag>
                    </div>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="经办人" prop="handler_id">
                    <el-select v-model="formData.handler_id" placeholder="请选择">
                        <el-option v-for="user in userList"
                                   :key="user.userId"
                                   :label="user.userName"
                                   :value="user.userId">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" v-model="formData.remark" rows="3"></el-input>
                </el-form-item>
            </el-col>
        </el-row>

        <!-- 盘点明细 -->
        <el-divider content-position="left">盘点明细</el-divider>
        <div class="detail-operations" style="margin-bottom: 10px;">
            <el-button type="primary" size="small" v-on:click="openProductDialog">添加货品</el-button>
            <el-button type="danger" size="small" v-on:click="removeDetail" :disabled="selectedDetails.length === 0">移除选中</el-button>
        </div>
        <el-table :data="detailList"
                  border
                  v-on:selection-change="handleDetailSelection"
                  style="width: 100%;">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column type="index" label="序号" width="60" fixed="left"></el-table-column>
            <el-table-column prop="product_code" label="货品编号" width="120" fixed="left">
                <template slot-scope="scope">
                    <span>{{ scope.row.product_code }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="product_name" label="货品名称" width="150" fixed="left">
                <template slot-scope="scope">
                    <span>{{ scope.row.product_name }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="spec" label="规格型号" width="120">
                <template slot-scope="scope">
                    <span>{{ scope.row.spec }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="product_type" label="货品类型" width="100">
                <template slot-scope="scope">
                    <span>{{ scope.row.product_type }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="book_quantity" label="账面库存" width="100" align="right">
                <template slot-scope="scope">
                    <span>{{ scope.row.book_quantity }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="book_amount" label="账面金额" width="110" align="right">
                <template slot-scope="scope">
                    <span>{{ scope.row.book_amount.toFixed(2) }}</span>
                </template>
            </el-table-column>
            <!-- 修改：盘点库位改为下拉选择框 -->
            <el-table-column prop="check_location" label="盘点库位" width="120" fixed="left">
                <template slot-scope="scope">
                    <el-select v-model="scope.row.check_location"
                               size="mini"
                               placeholder="选择库位"
                               filterable
                               clearable
                               v-on:change="validateDetail(scope.row)"
                               style="width: 100%;">
                        <el-option v-for="location in storageLocationList"
                                   :key="location.location_id"
                                   :label="location.location_name"
                                   :value="location.location_name">
                            <span>{{ location.location_name }}</span>
                            <span v-if="location.location_number" style="float: right; color: #8492a6; font-size: 12px">
                                ({{ location.location_number }})
                            </span>
                        </el-option>
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column prop="reference_price" label="参考单价" width="100" align="right">
                <template slot-scope="scope">
                    <span>{{ scope.row.reference_price.toFixed(2) }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="check_quantity" label="盘点数量" width="140" align="center">
                <template slot-scope="scope">
                    <el-input-number v-model="scope.row.check_quantity"
                                     size="mini"
                                     :min="0"
                                     v-on:change="calcProfitLoss(scope.row)">
                    </el-input-number>
                </template>
            </el-table-column>
            <el-table-column prop="profit_loss_num" label="盈亏数量" width="100" align="right">
                <template slot-scope="scope">
                    <span :style="getProfitLossNumStyle(scope.row.profit_loss_num)">
                        {{ scope.row.profit_loss_num || 0 }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="profit_loss_amount" label="盈亏金额" width="110" align="right">
                <template slot-scope="scope">
                    <span :style="getProfitLossAmountStyle(scope.row.profit_loss_amount)">
                        {{ (scope.row.profit_loss_amount || 0).toFixed(2) }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="check_status" label="盘点状态" width="100">
                <template slot-scope="scope">
                    <span :style="getCheckStatusStyle(scope.row.check_status)">
                        {{ scope.row.check_status }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" width="150">
                <template slot-scope="scope">
                    <el-input v-model="scope.row.remark" size="mini"></el-input>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="80" align="center" fixed="right">
                <template slot-scope="scope">
                    <el-button type="text"
                               size="small"
                               style="color: #ff4d4f;"
                               v-on:click="removeCurrentDetail(scope.row)">
                        移除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 合计信息 -->
        <div style="margin-top: 10px; text-align: right;">
            <el-descriptions column="6" border>
                <el-descriptions-item label="账面总库存">{{ totalBookQuantity }}</el-descriptions-item>
                <el-descriptions-item label="盘点总数量">{{ totalCheckQuantity }}</el-descriptions-item>
                <el-descriptions-item label="总盘盈数量">{{ totalProfit }}</el-descriptions-item>
                <el-descriptions-item label="总盘亏数量">{{ totalLoss }}</el-descriptions-item>
                <el-descriptions-item label="总盘盈金额">{{ totalProfitAmount.toFixed(2) }}</el-descriptions-item>
                <el-descriptions-item label="总盘亏金额">{{ totalLossAmount.toFixed(2) }}</el-descriptions-item>
            </el-descriptions>
        </div>
    </el-form>

    <!-- 提交按钮区域：移除保存为草稿，只保留关闭和保存提交审核 -->
    <div style="margin-top: 20px; text-align: right;">
        <el-button v-on:click="goBack">关闭</el-button>
        <el-button type="primary" v-on:click="saveForm">保存并提交审核</el-button>
    </div>

    <!-- 添加货品弹窗 -->
    <el-dialog title="选择货品"
               :visible.sync="showSelectProductDialog"
               width="900px"
               :close-on-click-modal="false">

        <!-- 弹窗搜索区 -->
        <div class="search-bar" style="margin-bottom: 15px;">
            <el-input v-model="productSearch.keyword"
                      placeholder="输入货品编号/名称搜索"
                      style="width: 300px; margin-right: 10px;"
                      v-on:keyup.enter.native="searchProducts">
            </el-input>
            <el-button type="primary" v-on:click="searchProducts">查询</el-button>
            <el-button v-on:click="resetProductSearch">重置</el-button>
        </div>

        <!-- 货品列表 -->
        <el-table :data="productList"
                  border
                  v-on:selection-change="handleProductSelection"
                  style="width: 100%;">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column type="index" label="序号" width="60"></el-table-column>
            <el-table-column prop="product_code" label="货品编号" width="120"></el-table-column>
            <el-table-column prop="product_name" label="货品名称" width="180"></el-table-column>
            <el-table-column prop="specification_model" label="规格型号" width="150"></el-table-column>
            <el-table-column prop="product_type_name" label="货品类型" width="120"></el-table-column>
            <!-- 关键修改：outrefprc → stkInrefp -->
            <el-table-column prop="stkInrefp" label="参考单价" width="100" align="right">
                <template slot-scope="scope">{{ scope.row.stkInrefp.toFixed(2) }}</template>
            </el-table-column>
            <el-table-column prop="current_stock" label="当前库存" width="100" align="right"></el-table-column>
        </el-table>

        <!-- 分页 -->
        <div style="margin-top: 10px; text-align: right;">
            <el-pagination v-on:size-change="handleProductSizeChange"
                           v-on:current-change="handleProductCurrentChange"
                           :current-page="productPage.pageNum"
                           :page-sizes="[10, 20, 50]"
                           :page-size="productPage.pageSize"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="productPage.total">
            </el-pagination>
        </div>

        <!-- 弹窗按钮 -->
        <div slot="footer">
            <el-button v-on:click="showSelectProductDialog = false">取消</el-button>
            <el-button type="primary" v-on:click="confirmSelectProducts">确认添加</el-button>
        </div>
    </el-dialog>
</div>

<!-- 引入依赖 -->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/element-ui@2.15.13/lib/index.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/element-ui@2.15.13/lib/theme-chalk/index.css">

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                loading: false,
                formData: {
                    inventory_order_no: '',
                    inventory_types: '',
                    inventory_start_time: '',
                    stkt_end_time: '',
                    warehouse_name: '',
                    handler_id: '',
                    remark: '',
                    check_location: ''
                },
                warehouseList: [],
                userList: [],
                storageLocationList: [],
                formRules: {
                    inventory_order_no: [{ required: true, message: '请生成盘点单号', trigger: 'blur' }],
                    inventory_types: [{ required: true, message: '请选择盘点类型', trigger: 'change' }],
                    inventory_start_time: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
                    stkt_end_time: [
                        { required: true, message: '请选择结束时间', trigger: 'change' }
                    ],
                    warehouse_name: [{ required: true, message: '请选择仓库', trigger: 'change' }],
                    handler_id: [{ required: true, message: '请选择经办人', trigger: 'change' }],
                    check_location: [{ required: false, message: '请选择库位', trigger: 'change' }]
                },
                detailList: [],
                selectedDetails: [],
                totalBookQuantity: 0,
                totalCheckQuantity: 0,
                totalProfit: 0,
                totalLoss: 0,
                totalProfitAmount: 0,
                totalLossAmount: 0,
                warehouseLocked: false,
                showSelectProductDialog: false,
                productSearch: { keyword: '' },
                productList: [],
                selectedProducts: [],
                productPage: { pageNum: 1, pageSize: 10, total: 0 },
                invalidDetailIds: []
            };
        },
        mounted() {
            console.log('🚀 页面初始化开始');

            // 添加仓库选择监听
            this.$watch('formData.warehouse_name', (newVal, oldVal) => {
                console.log(`🔄 仓库选择变化: ${oldVal} → ${newVal}`);
                if (newVal) {
                    console.log(`📋 开始获取仓库 ${newVal} 的库位数据`);
                }
            });

            // 添加库位列表监听
            this.$watch('storageLocationList', (newVal) => {
                console.log('📋 库位列表更新，当前库位:', newVal);
                if (newVal && newVal.length > 0) {
                    console.log('可用库位:', newVal.map(loc => loc.location_name).join(', '));
                }
            });

            this.formRules.stkt_end_time.push({
                validator: this.validateEndTime.bind(this),
                trigger: 'change'
            });
            this.getWarehouses();
            this.getUsers();
            this.generateOrderNo();
            this.setDefaultDates();

            console.log('✅ 页面初始化完成');

            // 添加明细数据监听（调试用）
            this.$watch('detailList', (newVal) => {
                console.log('📋 明细列表发生变化，当前条数:', newVal.length);
                newVal.forEach((item, index) => {
                    console.log(`   明细 ${index + 1}: ${item.product_code}, 账面=${item.book_quantity}, 盘点=${item.check_quantity}`);
                });
            }, { deep: true });
        },
        methods: {
            // ========== 样式方法 ==========
            getProfitLossNumStyle(profitLossNum) {
                if (profitLossNum > 0) return 'color: #67c23a; font-weight: bold;';
                if (profitLossNum < 0) return 'color: #f56c6c; font-weight: bold;';
                return 'color: #409eff; font-weight: bold;';
            },
            getProfitLossAmountStyle(profitLossAmount) {
                if (profitLossAmount > 0) return 'color: #67c23a; font-weight: bold;';
                if (profitLossAmount < 0) return 'color: #f56c6c; font-weight: bold;';
                return 'color: #409eff; font-weight: bold;';
            },
            getCheckStatusStyle(checkStatus) {
                if (checkStatus === '盘盈') return 'color: #67c23a; font-weight: bold;';
                if (checkStatus === '盘亏') return 'color: #f56c6c; font-weight: bold;';
                return 'color: #409eff; font-weight: bold;';
            },

            // ========== 表单验证方法 ==========
            validateEndTime(rule, value, callback) {
                if (!value) return callback();
                if (!this.formData.inventory_start_time) return callback(new Error('请先选择开始时间'));
                const startTime = new Date(this.formData.inventory_start_time);
                const endTime = new Date(value);
                if (endTime <= startTime) return callback(new Error('结束时间必须晚于开始时间'));
                callback();
            },
            setDefaultDates() {
                const now = new Date();
                const endTime = new Date(now.getTime() + 24 * 60 * 60 * 1000);
                this.formData.inventory_start_time = this.formatDate(now);
                this.formData.stkt_end_time = this.formatDate(endTime);
            },
            formatDate(date) {
                const y = date.getFullYear();
                const m = (date.getMonth() + 1).toString().padStart(2, '0');
                const d = date.getDate().toString().padStart(2, '0');
                return `${y}-${m}-${d}`;
            },

            // ========== 数据获取方法 ==========
            getWarehouses() {
                this.loading = true;
                const _this = this;
                console.log('🔄 开始获取仓库列表');
                $.get('/InventoryCheck/GetAllWarehouses', function(res) {
                    _this.loading = false;
                    console.log('📥 仓库列表接口返回:', res);
                    if (res.success) {
                        _this.warehouseList = res.data || [];
                        console.log('✅ 获取仓库列表成功，条数：' + _this.warehouseList.length);
                        if (_this.warehouseList.length > 0 && !_this.formData.warehouse_name) {
                            _this.formData.warehouse_name = _this.warehouseList[0].warehouse_name;
                            _this.checkWarehouseLock(_this.formData.warehouse_name);
                        }
                    } else {
                        console.error('❌ 获取仓库列表失败：' + res.message);
                        _this.$message.error('获取仓库列表失败：' + res.message);
                    }
                }).fail(() => {
                    _this.loading = false;
                    console.error('❌ 获取仓库列表网络错误');
                    _this.$message.error('获取仓库列表失败，网络错误');
                });
            },
            getUsers() {
                this.loading = true;
                const _this = this;
                console.log('🔄 开始获取用户列表');
                $.get('/InventoryCheck/GetAllUsers', function(res) {
                    _this.loading = false;
                    console.log('📥 用户列表接口返回:', res);
                    if (res.success) {
                        _this.userList = res.data || [];
                        console.log('✅ 获取用户列表成功，条数：' + _this.userList.length);
                    } else {
                        console.error('❌ 获取用户列表失败：' + res.message);
                        _this.$message.error('获取用户列表失败：' + res.message);
                    }
                }).fail(() => {
                    _this.loading = false;
                    console.error('❌ 获取用户列表网络错误');
                    _this.$message.error('获取用户列表失败，网络错误');
                });
            },

            // ========== 库位相关方法 ==========
            // 根据仓库获取库位
            getStorageLocationsByWarehouse(warehouseName) {
                if (!warehouseName) {
                    this.storageLocationList = [];
                    this.formData.check_location = '';
                    return;
                }

                const _this = this;
                console.log('🔄 开始调用GetStorageLocationsByWarehouse接口，仓库名称:', warehouseName);

                // 🔴 关键修复：确保参数名称正确
                $.get('/InventoryCheck/GetStorageLocationsByWarehouse', { warehouseName: warehouseName }, function(res) {
                    console.log('📥 GetStorageLocationsByWarehouse接口返回:', res);
                    if (res.success) {
                        _this.storageLocationList = res.data || [];
                        console.log(`✅ 获取仓库 ${warehouseName} 的库位成功，条数：` + _this.storageLocationList.length);

                        // 关键修改：设置默认库位逻辑
                        if (_this.storageLocationList.length > 0) {
                            // 只设置表单级别的默认库位，明细级别的在添加货品时单独设置
                            _this.formData.check_location = _this.storageLocationList[0].location_name;
                            console.log(`✅ 设置表单默认库位: ${_this.formData.check_location}`);
                        } else {
                            console.warn(`⚠️ 仓库 ${warehouseName} 没有对应的库位数据`);
                            _this.formData.check_location = '';
                            _this.$message.warning(`仓库 ${warehouseName} 没有配置库位`);
                        }
                    } else {
                        console.error('❌ 获取库位列表失败：' + res.message);
                        _this.$message.error('获取库位列表失败：' + res.message);
                        _this.storageLocationList = [];
                        _this.formData.check_location = '';
                    }
                }).fail((xhr, status, error) => {
                    console.error('❌ GetStorageLocationsByWarehouse接口调用失败:', {
                        status: xhr.status,
                        statusText: xhr.statusText,
                        responseText: xhr.responseText,
                        error: error
                    });
                    _this.$message.error('获取库位列表失败，网络错误');
                    _this.storageLocationList = [];
                    _this.formData.check_location = '';
                });
            },

            // ========== 其他业务方法 ==========
            goBack() {
                window.location.href = '/InventoryCheck/Index';
            },
            generateOrderNo() {
                console.log('🔄 调用GenerateBusinessNumber接口');
                this.loading = true;
                const _this = this;
                $.post('/InventoryCheck/GenerateBusinessNumber', {}, function(res) {
                    _this.loading = false;
                    console.log('📥 生成单号接口返回:', res);
                    if (res.success) {
                        _this.formData.inventory_order_no = res.businessNumber;
                        console.log('✅ 单号生成成功：' + res.businessNumber);
                    } else {
                        console.error('❌ 生成单号失败：' + res.message);
                        _this.$message.error(res.message || '生成单号失败');
                    }
                }).fail(() => {
                    _this.loading = false;
                    console.error('❌ 生成单号网络错误');
                    _this.$message.error('生成单号失败，网络错误');
                });
            },
            checkWarehouseLock(warehouseName) {
                if (!warehouseName) {
                    this.warehouseLocked = false;
                    this.storageLocationList = [];
                    this.formData.check_location = '';
                    return;
                }

                const _this = this;
                console.log('🔄 检查仓库锁定状态，仓库名称:', warehouseName);

                $.get('/InventoryCheck/CheckWarehouseLock', { warehouseName }, function(res) {
                    console.log('📥 检查仓库锁定状态返回:', res);
                    if (res.success) {
                        _this.warehouseLocked = res.isLocked;
                        console.log(`✅ 仓库 ${warehouseName} 锁定状态: ${res.isLocked}`);

                        // 🔴 关键修复：确保传递正确的仓库名称
                        _this.getStorageLocationsByWarehouse(warehouseName);

                        if (!res.isLocked) {
                            _this.$confirm('仓库未锁定，可能导致数据不一致，是否前往锁定？', '提示', {
                                confirmButtonText: '去锁定',
                                cancelButtonText: '取消',
                                type: 'warning'
                            }).then(() => {
                                window.location.href = '/Warehouse/Index';
                            }).catch(() => {
                                console.log('❌ 用户取消跳转');
                            });
                        }
                    } else {
                        console.error('❌ 检查仓库状态失败：' + res.message);
                        _this.$message.error('检查仓库状态失败：' + res.message);
                    }
                }).fail(() => {
                    console.error('❌ 检查仓库状态网络错误');
                    _this.$message.error('检查仓库状态失败，网络错误');
                });
            },

            // ========== 货品选择相关方法 ==========
            openProductDialog() {
                this.selectedProducts = [];
                this.productSearch = { keyword: '' };
                this.productPage.pageNum = 1;
                this.showSelectProductDialog = true;
                this.searchProducts();
            },
            // 修改搜索方法，正确获取当前选择的库位
            searchProducts() {
                const _this = this;

                // 🔴 关键修复：使用当前选择的库位
                const currentLocation = this.formData.check_location;

                const params = {
                    Keyword: this.productSearch.keyword,
                    PageNum: this.productPage.pageNum,
                    PageSize: this.productPage.pageSize,
                    WarehouseName: this.formData.warehouse_name,
                    Location: currentLocation // 使用当前选择的库位
                };

                console.log('🔄 搜索货品，参数:', params, '当前库位:', currentLocation);

                $.get('/InventoryCheck/Search', params, function(res) {
                    console.log('📥 搜索货品返回:', res);
                    if (res.success) {
                        _this.productList = res.data.list || [];
                        _this.productPage.total = res.data.total || 0;
                        console.log('✅ 搜索货品成功，条数：' + _this.productList.length);

                        // 打印库存信息用于调试
                        _this.productList.forEach(product => {
                            console.log(`货品 ${product.product_code} 当前库存: ${product.current_stock} (库位: ${currentLocation})`);
                        });
                    } else {
                        console.error('❌ 搜索货品失败：' + res.message);
                        _this.$message.error('搜索货品失败：' + res.message);
                    }
                }).fail((xhr) => {
                    console.error('❌ 搜索货品网络错误:', xhr.statusText);
                    _this.$message.error('搜索失败：' + xhr.statusText);
                });
            },
            resetProductSearch() {
                this.productSearch = { keyword: '' };
                this.productPage.pageNum = 1;
                this.searchProducts();
            },
            handleProductSelection(val) {
                this.selectedProducts = val;
                console.log('📋 选中货品数量:', val.length);
            },
            handleProductSizeChange(size) {
                this.productPage.pageSize = size;
                this.productPage.pageNum = 1;
                this.searchProducts();
            },
            handleProductCurrentChange(page) {
                this.productPage.pageNum = page;
                this.searchProducts();
            },
            // 修改 confirmSelectProducts 方法
            confirmSelectProducts() {
                if (this.selectedProducts.length === 0) {
                    this.$message.warning('请选择货品');
                    return;
                }
                const existingCodes = this.detailList.map(item => item.product_code);
                const newProducts = this.selectedProducts.filter(p => !existingCodes.includes(p.product_code));
                if (newProducts.length === 0) {
                    this.$message.warning('选中的货品已全部添加');
                    this.showSelectProductDialog = false;
                    return;
                }

                // 🔴 关键修复：使用当前选择的仓库对应的库位
                const currentLocation = this.formData.check_location;

                if (!currentLocation) {
                    this.$message.warning('请先选择盘点库位');
                    return;
                }

                console.log('🔄 添加货品到明细，数量:', newProducts.length, '当前库位:', currentLocation);

                // 按库位刷新库存
                this.refreshProductStocks(newProducts, currentLocation).then(updatedProducts => {
                    updatedProducts.forEach(product => {
                        const latestStock = product.current_stock;

                        console.log(`📝 正在添加货品 ${product.product_code}:`);
                        console.log(`   最新库存: ${latestStock} (库位: ${currentLocation})`);
                        console.log(`   参考单价: ${product.stkInrefp}`);
                        console.log(`   账面金额: ${(latestStock * product.stkInrefp).toFixed(2)}`);

                        const newDetail = {
                            product_code: product.product_code,
                            product_name: product.product_name,
                            spec: product.specification_model,
                            product_type: product.product_type_name,
                            book_quantity: latestStock,
                            book_amount: (latestStock * product.stkInrefp).toFixed(2) * 1,
                            check_location: currentLocation, // 使用当前选择的库位
                            reference_price: product.stkInrefp,
                            check_quantity: latestStock,
                            profit_loss_num: 0,
                            profit_loss_amount: 0,
                            check_status: '无盈亏',
                            remark: ''
                        };

                        console.log(`✅ 添加明细数据:`, newDetail);
                        this.detailList.push(newDetail);
                    });

                    this.calcTotal();
                    this.showSelectProductDialog = false;
                    this.$message.success(`成功添加 ${newProducts.length} 条货品`);
                });
            },

            // 修改 refreshProductStocks 方法中的接口调用
            refreshProductStocks(products, location) {
                return new Promise((resolve) => {
                    const productCodes = products.map(p => p.product_code);
                    console.log('🔄 按库位刷新货品库存数据:', productCodes, '库位:', location);

                    // 添加仓库和库位参数
                    const params = {
                        productCodes: productCodes.join(','),
                        warehouseName: this.formData.warehouse_name,
                        location: location // 添加库位参数
                    };

                    console.log('📤 库存查询参数:', params);

                    // 修改：使用正确的 GetProductStocks 接口
                    $.get('/InventoryCheck/GetProductStocks', params, (res) => {
                        console.log('📥 库存刷新接口返回:', res);
                        if (res.success && res.data) {
                            const stockMap = res.data;
                            const updatedProducts = products.map(product => {
                                const newStock = stockMap[product.product_code];
                                console.log(`   货品 ${product.product_code}: 原库存=${product.current_stock}, 新库存=${newStock}`);

                                if (newStock !== undefined) {
                                    return {
                                        ...product,
                                        current_stock: newStock
                                    };
                                }
                                return product;
                            });
                            console.log('✅ 货品库存数据刷新完成');
                            resolve(updatedProducts);
                        } else {
                            console.warn('⚠️ 获取货品库存失败，使用搜索接口数据');
                            resolve(products);
                        }
                    }).fail((xhr, status, error) => {
                        console.warn('⚠️ 获取货品库存接口失败，使用搜索接口数据:', error);
                        resolve(products);
                    });
                });
            },

            // ========== 明细操作相关方法 ==========
            removeDetail() {
                const originalLength = this.detailList.length;
                this.detailList = this.detailList.filter(item => !this.selectedDetails.includes(item));
                this.selectedDetails = [];
                this.calcTotal();
                const removedCount = originalLength - this.detailList.length;
                console.log('🗑️ 移除选中明细，数量:', removedCount);
                this.$message.success(`移除 ${removedCount} 条明细`);
            },
            removeCurrentDetail(row) {
                this.detailList = this.detailList.filter(item => item !== row);
                this.calcTotal();
                console.log('🗑️ 移除单条明细');
                this.$message.success('已移除该明细');
            },
            handleDetailSelection(val) {
                this.selectedDetails = val;
            },

            // 关键修改：在库位变更时重新获取库存
            validateDetail(row) {
                const errors = [];
                if (!row.check_location) errors.push('盘点库位不能为空');
                if (row.check_quantity === null || row.check_quantity < 0) errors.push('盘点数量不能为负');

                const rowIndex = this.detailList.indexOf(row);
                if (errors.length > 0) {
                    if (!this.invalidDetailIds.includes(rowIndex)) this.invalidDetailIds.push(rowIndex);
                    console.warn('❌ 明细验证失败:', errors);
                } else {
                    this.invalidDetailIds = this.invalidDetailIds.filter(id => id !== rowIndex);

                    // 关键修改：当库位变更时，重新获取该货品在新库位下的库存
                    if (row.product_code && row.check_location) {
                        this.refreshSingleProductStock(row);
                    }
                }
            },

            // 修改 refreshSingleProductStock 方法中的接口调用
            refreshSingleProductStock(row) {
                console.log(`🔄 刷新单个货品库存: ${row.product_code}, 新库位: ${row.check_location}`);

                const params = {
                    productCodes: row.product_code,
                    warehouseName: this.formData.warehouse_name,
                    location: row.check_location
                };

                // 修改：使用正确的 GetProductStocks 接口
                $.get('/InventoryCheck/GetProductStocks', params, (res) => {
                    console.log('📥 单个货品库存刷新接口返回:', res);
                    if (res.success && res.data) {
                        const newStock = res.data[row.product_code];
                        console.log(`   货品 ${row.product_code} 在新库位 ${row.check_location} 的库存: ${newStock}`);

                        if (newStock !== undefined) {
                            // 更新账面库存和账面金额
                            const oldBookQuantity = row.book_quantity;
                            row.book_quantity = newStock;
                            row.book_amount = (newStock * row.reference_price).toFixed(2) * 1;

                            console.log(`  库存更新: ${oldBookQuantity} → ${newStock}`);

                            // 重新计算盈亏
                            this.calcProfitLoss(row);
                        } else {
                            console.warn(`⚠️ 未获取到货品 ${row.product_code} 在库位 ${row.check_location} 的库存`);
                            row.book_quantity = 0;
                            row.book_amount = 0;
                            this.calcProfitLoss(row);
                        }
                    } else {
                        console.warn('⚠️ 获取单个货品库存失败，保持原库存');
                    }
                }).fail((xhr, status, error) => {
                    console.warn('⚠️ 获取单个货品库存接口失败:', error);
                });
            },

            calcProfitLoss(row) {
                console.log(`📝 开始计算盈亏: ${row.product_code}`);
                console.log(`   账面库存: ${row.book_quantity}, 盘点数量: ${row.check_quantity}`);

                // 强制校验：盘点数量不能为null/undefined，且不能为负
                if (row.check_quantity == null || row.check_quantity < 0) {
                    row.check_quantity = 0;
                    this.$message.warning(`货品 ${row.product_code} 盘点数量异常，已重置为0`);
                }

                // 核心计算：盈亏数量=盘点数量-账面库存
                row.profit_loss_num = row.check_quantity - row.book_quantity;

                // 盈亏金额=盈亏数量×参考单价（确保参考单价不为0）
                row.reference_price = row.reference_price || 0;
                row.profit_loss_amount = row.profit_loss_num * row.reference_price;

                // 盘点状态
                if (row.profit_loss_num > 0) {
                    row.check_status = '盘盈';
                } else if (row.profit_loss_num < 0) {
                    row.check_status = '盘亏';
                } else {
                    row.check_status = '无盈亏';
                }

                console.log(`   盈亏数量: ${row.profit_loss_num}, 盈亏金额: ${row.profit_loss_amount.toFixed(2)}`);
                this.calcTotal(); // 同步更新汇总
            },

            calcTotal() {
                console.log('🔄 开始计算汇总数据...');

                // 重置所有汇总值
                this.totalBookQuantity = 0;
                this.totalCheckQuantity = 0;
                this.totalProfit = 0;
                this.totalLoss = 0;
                this.totalProfitAmount = 0;
                this.totalLossAmount = 0;

                // 遍历明细计算汇总
                this.detailList.forEach((item, index) => {
                    console.log(`🔢 明细 ${index + 1}: ${item.product_code}`);
                    console.log(`   账面库存: ${item.book_quantity}, 盘点数量: ${item.check_quantity}`);
                    console.log(`   盈亏数量: ${item.profit_loss_num}, 盈亏金额: ${item.profit_loss_amount}`);

                    // 账面总库存
                    this.totalBookQuantity += item.book_quantity || 0;

                    // 盘点总数量
                    this.totalCheckQuantity += item.check_quantity || 0;

                    // 盘盈数量（只计算正数）
                    if (item.profit_loss_num > 0) {
                        this.totalProfit += item.profit_loss_num;
                    }

                    // 盘亏数量（取绝对值）
                    if (item.profit_loss_num < 0) {
                        this.totalLoss += Math.abs(item.profit_loss_num);
                    }

                    // 盘盈金额（只计算正数）
                    if (item.profit_loss_amount > 0) {
                        this.totalProfitAmount += item.profit_loss_amount;
                    }

                    // 盘亏金额（取绝对值）
                    if (item.profit_loss_amount < 0) {
                        this.totalLossAmount += Math.abs(item.profit_loss_amount);
                    }
                });

                // 打印汇总结果
                console.log('📊 前端汇总计算结果：');
                console.log(`   账面总库存：${this.totalBookQuantity}`);
                console.log(`   盘点总数量：${this.totalCheckQuantity}`);
                console.log(`   总盘盈数量：${this.totalProfit}`);
                console.log(`   总盘亏数量：${this.totalLoss}`);
                console.log(`   总盘盈金额：${this.totalProfitAmount.toFixed(2)}`);
                console.log(`   总盘亏金额：${this.totalLossAmount.toFixed(2)}`);
            },

            // ========== 保存提交方法 ==========
            saveForm() {
                const _this = this;
                console.log('💾 开始保存表单，直接提交审核（状态：待审核）');

                this.$refs.formRef.validate((valid) => {
                    if (!valid) {
                        console.error('❌ 表单验证失败');
                        return;
                    }
                    if (this.detailList.length === 0) {
                        console.warn('⚠️ 明细为空');
                        this.$message.warning('请添加盘点明细');
                        return;
                    }
                    if (this.invalidDetailIds.length > 0) {
                        console.warn('⚠️ 存在无效明细数据');
                        this.$message.warning('明细存在无效数据，请检查');
                        return;
                    }

                    if (!this.warehouseLocked) {
                        console.warn('⚠️ 仓库未锁定，禁止提交审核');
                        this.$alert('仓库未锁定，可能导致数据不一致，无法继续提交审核，请先锁定仓库', '提示', {
                            confirmButtonText: '去锁定',
                            type: 'warning',
                            showCancelButton: false
                        }).then(() => {
                            window.location.href = '/Warehouse/Index';
                        });
                        return;
                    }
                    this.submitForm();
                });
            },
            submitForm() {
                this.loading = true;
                const _this = this;

                // 关键修改：确保提交的数据格式与后端一致
                const submitData = {
                    inventory_order_no: this.formData.inventory_order_no,
                    inventory_types: this.formData.inventory_types,
                    inventory_start_time: this.formData.inventory_start_time,
                    stkt_end_time: this.formData.stkt_end_time,
                    warehouse_name: this.formData.warehouse_name,
                    handler_id: this.formData.handler_id?.toString(),
                    note: this.formData.remark,
                    review_status: 1, // 固定设为待审核状态
                    outbound_status: "0",
                    reviewer: "",

                    // 关键修改：使用前端计算的正数汇总值
                    total_profit_num: this.totalProfit,        // 盘盈数量（正数）
                    total_loss_num: this.totalLoss,            // 盘亏数量（正数）
                    total_profit_amount: this.totalProfitAmount, // 盘盈金额（正数）
                    total_loss_amount: this.totalLossAmount,   // 盘亏金额（正数）

                    details: this.detailList.map(item => ({
                        product_code: item.product_code,
                        product_name: item.product_name,
                        spec: item.spec,
                        product_type: item.product_type,
                        book_quantity: item.book_quantity,
                        book_amount: item.book_amount,
                        check_location: item.check_location, // 前端字段名
                        reference_price: item.reference_price, // 前端字段名
                        check_quantity: item.check_quantity, // 前端字段名
                        profit_loss_num: item.profit_loss_num, // 盈亏数量（可正可负）
                        profit_loss_amount: item.profit_loss_amount, // 盈亏金额（可正可负）
                        remark: item.remark,
                        check_status: item.check_status
                    }))
                };

                console.log('📤 提交数据验证：');
                console.log('   前端计算 - 总盘盈数量:', this.totalProfit);
                console.log('   前端计算 - 总盘亏数量:', this.totalLoss);
                console.log('   前端计算 - 总盘盈金额:', this.totalProfitAmount);
                console.log('   前端计算 - 总盘亏金额:', this.totalLossAmount);

                fetch('/InventoryCheck/CreateInventory', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(submitData)
                }).then(response => response.json())
                  .then(res => {
                      this.loading = false;
                      console.log('📥 提交结果:', res);
                      if (res.success) {
                          console.log('✅ 保存并提交审核成功');
                          console.log('   服务端计算 - 总盘盈数量:', res.calcResult?.totalProfitNum);
                          console.log('   服务端计算 - 总盘亏数量:', res.calcResult?.totalLossNum);
                          this.$message.success('创建成功，已提交审核');
                          this.goBack();
                      } else {
                          console.error('❌ 保存失败:', res.message);
                          this.$message.error(res.message || '保存失败');
                      }
                  }).catch(error => {
                      this.loading = false;
                      console.error('❌ 网络错误:', error);
                      this.$message.error('网络错误：' + error.message);
                  });
            }
        }
    });
</script>
<style>
    .container {
        padding: 20px;
    }

    .detail-operations {
        margin-bottom: 10px;
    }

    .search-bar {
        display: flex;
        align-items: center;
    }

    .el-table__fixed-right {
        height: 100% !important;
    }
</style>